package com.gewu.pm.ui.activity.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.ApprovalFlowBean;
import com.gewu.pm.bean.GoodsBean;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.adapter.order.ApprovalFlowAdapter;
import com.gewu.pm.ui.adapter.order.GoodsAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 销售订单详情页
 */
public final class SalesOrderDetailsActivity extends AppActivity {

    private static final int COLLAPSED_GOODS_COUNT = 3;  // 收起时显示的商品数量

    private TextView mTerminalNameView;// 终端信息
    private TextView mStatusView;
    private TextView mTerminalCodeView;
    private TextView mOrderNoView;
    private TextView mOrderTimeView;
    private TextView mDeliveryDateView;
    private TextView mOrderDateView;
    private TextView mPromotionTypeView;
    private TextView mPromotionNameView;
    private TextView mVehicleCodeView;
    private TextView mDeliveryMerchantView;
    private TextView mSalespersonView;
    private TextView mSalesRegionView;
    private TextView mDepartmentView;
    private RecyclerView mGoodsRecyclerView;// 商品清单
    private LinearLayout mToggleGoodsLayout;
    private TextView mToggleTextView;
    private ImageView mToggleArrowView;
    private TextView mTotalQuantityView;// 订单金额
    private TextView mTotalAmountView;
    private TextView mDiscountAmountView;
    private TextView mOrderAmountView;
    private LinearLayout mDeliveryRecordLayout;// 记录
    private LinearLayout mReduceRecordLayout;
    private RecyclerView mApprovalFlowRecyclerView;// 审批流程
    private TextView mSubmitButton;// 底部按钮

    private GoodsAdapter mGoodsAdapter;//用的是商品列表的，布局有点不一样 修要修改
    private ApprovalFlowAdapter mApprovalFlowAdapter;

    /** 所有商品列表 */
    private List<GoodsBean> mAllGoodsList = new ArrayList<>();
    /** 是否展开商品列表 */
    private boolean mIsGoodsExpanded = false;

    /**
     * 启动订单详情页
     *
     * @param context 上下文
     * @param status 订单状态
     * @param terminalName 终端名称
     */
    public static void start(Context context, String status, String terminalName) {
        Intent intent = new Intent(context, SalesOrderDetailsActivity.class);
        intent.putExtra(IntentKey.TYPE, status);
        intent.putExtra(IntentKey.TITLE, terminalName);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sales_order_details;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mTerminalNameView = findViewById(R.id.tv_terminal_name);
        mStatusView = findViewById(R.id.tv_status);
        mTerminalCodeView = findViewById(R.id.tv_terminal_code);
        mOrderNoView = findViewById(R.id.tv_order_no);
        mOrderTimeView = findViewById(R.id.tv_order_time);
        mDeliveryDateView = findViewById(R.id.tv_delivery_date);
        mOrderDateView = findViewById(R.id.tv_order_date);
        mPromotionTypeView = findViewById(R.id.tv_promotion_type);
        mPromotionNameView = findViewById(R.id.tv_promotion_name);
        mVehicleCodeView = findViewById(R.id.tv_vehicle_code);
        mDeliveryMerchantView = findViewById(R.id.tv_delivery_merchant);
        mSalespersonView = findViewById(R.id.tv_salesperson);
        mSalesRegionView = findViewById(R.id.tv_sales_region);
        mDepartmentView = findViewById(R.id.tv_department);

        mGoodsRecyclerView = findViewById(R.id.rv_goods);
        mToggleGoodsLayout = findViewById(R.id.ll_toggle_goods);
        mToggleTextView = findViewById(R.id.tv_toggle_text);
        mToggleArrowView = findViewById(R.id.iv_toggle_arrow);

        mTotalQuantityView = findViewById(R.id.tv_total_quantity);
        mTotalAmountView = findViewById(R.id.tv_total_amount);
        mDiscountAmountView = findViewById(R.id.tv_discount_amount);
        mOrderAmountView = findViewById(R.id.tv_order_amount);

        mDeliveryRecordLayout = findViewById(R.id.ll_delivery_record);
        mReduceRecordLayout = findViewById(R.id.ll_reduce_record);

        mApprovalFlowRecyclerView = findViewById(R.id.rv_approval_flow);

        mSubmitButton = findViewById(R.id.btn_submit);

        // 设置商品RecyclerView
        mGoodsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mGoodsRecyclerView.setNestedScrollingEnabled(false);  // 禁用列表滑动，随外层ScrollView滑动
        mGoodsAdapter = new GoodsAdapter(this);
        mGoodsAdapter.setShowDelete(false);  // 隐藏删除按钮
        mGoodsRecyclerView.setAdapter(mGoodsAdapter);

        // 设置审批流程RecyclerView
        mApprovalFlowRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mApprovalFlowRecyclerView.setNestedScrollingEnabled(false);  // 禁用列表滑动
        mApprovalFlowAdapter = new ApprovalFlowAdapter(this);
        mApprovalFlowRecyclerView.setAdapter(mApprovalFlowAdapter);

        // 设置点击监听（ll_toggle_goods 单独处理，不加防抖）
        mToggleGoodsLayout.setOnClickListener(v -> onToggleGoodsClick());
        
        // 其他点击添加防抖
        setOnClickListener(mDeliveryRecordLayout, mReduceRecordLayout, mSubmitButton);
    }

    @Override
    protected void initData() {
        // 获取 Intent 参数
        String status = getString(IntentKey.TYPE);
        String terminalName = getString(IntentKey.TITLE);

        // 设置终端名称和状态
        if (terminalName != null) {
            mTerminalNameView.setText(terminalName);
        }
        if (status != null) {
            mStatusView.setText(status);
        }

        // 加载测试数据
        loadMockData();
        loadMockGoods();
        loadMockApprovalFlow();

        // 初始显示收起状态
        updateGoodsDisplay();
    }

    /**
     * 加载模拟订单数据
     */
    private void loadMockData() {
        mTerminalCodeView.setText("POS00011718");
        mOrderNoView.setText("666643327895877");
        mOrderTimeView.setText("2025-08-11 13:12:13");
        mDeliveryDateView.setText("2025-08-12");
        mOrderDateView.setText("2025-08-11  19:00(跳转日期)");
        mPromotionTypeView.setText("/买赠/满减/优惠卷/租名豆");
        mPromotionNameView.setText("买豆腐送豆乳");
        mVehicleCodeView.setText("A12333");
        mDeliveryMerchantView.setText("小配送56号车");
        mSalespersonView.setText("霍辉");
        mSalesRegionView.setText("杭州-滨江");
        mDepartmentView.setText("销售部");

        // 订单金额
        mTotalQuantityView.setText("1箱2盒");
        mTotalAmountView.setText("¥56.53");
        mDiscountAmountView.setText("¥20.00");
        mOrderAmountView.setText("¥36.53");
    }

    /**
     * 加载模拟商品数据（6条）
     */
    private void loadMockGoods() {
        mAllGoodsList.clear();

        Random random = new Random();
        String[] names = {"有机豆腐", "五香豆干", "桂花酒酿", "纯生啤酒", "老干妈豆豉", "王致和腐乳"};
        String[] units = {"箱", "包", "盒", "瓶", "袋", "罐"};

        // 生成6条商品
        for (int i = 0; i < 6; i++) {
            GoodsBean goods = new GoodsBean();
            goods.setId("goods_" + i);
            goods.setName(names[i]);
            goods.setTag(random.nextBoolean() ? "促销" : null);
            goods.setSellingPoint("轻食搭档皮薄多汁|健康解馋选择");
            goods.setStock(random.nextInt(11));
            goods.setShelfLife("冷藏8天");
            goods.setCode("1011010" + String.format("%02d", i));
            goods.setPrice("¥" + (10 + random.nextInt(40)) + "." + random.nextInt(10));
            goods.setUnit(units[i % units.length]);
            goods.setQuantity(random.nextInt(5) + 1);  // 数量1-5

            mAllGoodsList.add(goods);
        }
    }

    /**
     * 加载模拟审批流程（参考TelegraphicDetailsActivity第140行）
     */
    private void loadMockApprovalFlow() {
        List<ApprovalFlowBean> flowList = new ArrayList<>();
        flowList.add(new ApprovalFlowBean("2025/8/18 16:00", "霍辉·已提交"));
        flowList.add(new ApprovalFlowBean("2025/8/18 16:30", "审批·已通过"));
        flowList.add(new ApprovalFlowBean("2025/8/18 17:00", "财务·审核中"));
        mApprovalFlowAdapter.setData(flowList);
    }

    /**
     * 更新商品显示（展开/收起）
     */
    private void updateGoodsDisplay() {
        List<GoodsBean> displayList = new ArrayList<>();

        if (mIsGoodsExpanded || mAllGoodsList.size() <= COLLAPSED_GOODS_COUNT) {
            // 展开状态或商品数<=3，显示全部
            displayList.addAll(mAllGoodsList);
            mToggleGoodsLayout.setVisibility(mAllGoodsList.size() > COLLAPSED_GOODS_COUNT ? View.VISIBLE : View.GONE);

            if (mAllGoodsList.size() > COLLAPSED_GOODS_COUNT) {
                mToggleTextView.setText("收起清单");
                mToggleArrowView.setImageResource(R.drawable.arrow_shang);  // 向上箭头
            }
        } else {
            // 收起状态，只显示前3条
            for (int i = 0; i < Math.min(COLLAPSED_GOODS_COUNT, mAllGoodsList.size()); i++) {
                displayList.add(mAllGoodsList.get(i));
            }
            mToggleGoodsLayout.setVisibility(View.VISIBLE);

            int remainCount = mAllGoodsList.size() - COLLAPSED_GOODS_COUNT;
            mToggleTextView.setText("还有" + remainCount + "种商品");
            mToggleArrowView.setImageResource(R.drawable.arrow_xia);  // 向下箭头
        }

        mGoodsAdapter.setData(displayList);
        mGoodsAdapter.notifyDataSetChanged();

    }

    /**
     * 切换商品展开/收起（不加防抖）
     */
    private void onToggleGoodsClick() {
        mIsGoodsExpanded = !mIsGoodsExpanded;
        updateGoodsDisplay();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.ll_delivery_record) {
            // 发货记录
            toast("查看发货记录");

        } else if (viewId == R.id.ll_reduce_record) {
            // 减货记录
            toast("查看减货记录");

        } else if (viewId == R.id.btn_submit) {
            // 关闭订单
            toast("关闭订单");
            finish();
        }
    }

}

